<template>
    <div class="ReportSound_div">
        <a-row id="ReportSound_row2" class="ReportImage_row1">
            <a-col :span="24" class="ReportImage_col">
                <el-button type="info" id="ReportSound_btn" v-on:click="takeVoice"  class="ReportImage_btn1" clickMusic="true">
                    录音
                </el-button>
            </a-col>
        </a-row>

        <a-row id="ReportSound_row1" class="ReportImage_row1">
            <a-col :span="24" class="ReportImage_col">
                <el-button type="info" id="ReportSound_btn1"  v-on:click="chooseAudio" class="ReportImage_btn1">
                    本地选择
                </el-button>
            </a-col>
        </a-row>
        <a-row :span="24" class="showTextCol">
            <div class="showTextOkDiv" v-if="isOk==='1'">{{myFileName}}<br/>上传录音成功</div>
            <div class="showTextFailDiv" v-if="isOk==='0'">{{myFileName}}<br/>上传录音失败</div>
        </a-row>
        <div class="showBox" v-if="Loading" >
            <div class="loading"></div>
            <div class="progress_div">{{progress}}</div>
        </div>
    </div>
</template>
<style>

    @keyframes loading {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    .showBox{
        padding: 45vh 0 0 0 ;
        width: 100vw;
        height: 100vh;
        background: rgba(0,0,0,0.5);
        z-index: 100;
        top: 0;
        left: 0;
        position: absolute;
    }
    .ReportSound_div{
        background: rgba(237,237,237,0.3);
        min-height: 100vh;
        width: 100vw;
        padding-top: 5vw;
    }
    #ReportSound_btn1{
        margin: 5vw 0 2vw 0;
    }
</style>
<script>
    import ARow from "ant-design-vue/es/grid/Row";
    import axios from 'axios';
    import {mapState} from "vuex";
    export default {
        name: "ReportSound",
        components: {ARow},
        computed:{
            ...mapState([
                'Loading'
            ])
        },
        data() {
            return {
                msg: 'hello vue',
                latitude:localStorage.getItem("latitude")?localStorage.getItem("latitude"):"0",
                longitude:localStorage.getItem("longitude")?localStorage.getItem("longitude"):"0",
                sid:localStorage.getItem("sid"),
                workModeId:localStorage.getItem("workModeId"),
                Authorization:localStorage.getItem("userToken"),
                reportHistory:localStorage.getItem("reportHistory")?JSON.parse(localStorage.getItem("reportHistory")):[],
                myVideoInfo:{ },
                isOk:"",
                myFile:'',
                gis4_imei:localStorage.getItem("gis4_imei"),
                gis4_phone:localStorage.getItem("gis4_phone"),
                createTime:"",
                progress:'',//上传文件的进度
                myFileName:'',//获取到的当前文件名
                path:'',//获取到的当前文件全路径
                file:'',//获取到的当前文件

            }
        },
    methods: {
            //新方法多媒体选择器录音/选择上传
            takeVoice(){
                let me = this;
                console.log('我要录制录音');
                let success = function(result){
                    console.log("选择录音成功:",result);
                    if (result.length > 0) {
                        me.$store.commit('showLoading'); //打开遮罩
                        console.log("选择录音成功",result);
                        //返回的数据一个为jsonArray，一个图片有未压缩地址filePath和压缩地址compressPath，循环得乘以2
                        for(let i = 0;i<(result.length)/2;i++){
                            me.path = result[2*i+1];//这里取压缩地址，未压缩地址为：result[2*i]
                            let arrName = result[2*i+1].split("/");
                            me.myFileName = arrName[(arrName.length) - 1];
                            me.getLocaltion();
                        }
                    }
                };
                let fail = function(error){
                    console.log("返回Voice选择结果失败:",error);
                    me.$store.commit("hideLoading");
                };
                myMediaPlugin.takeVoice(success,fail,{message:"随便"});
            },
        getAudio() {
            //this.clickButton();
            let me = this;
            //录制失败
            function onError(error) {
                me.$store.commit('hideLoading');//打开遮罩
                console.log('录制失败！错误码：' + error.code);

            }

            //录制成功 {duration: 60}
            function onSuccess(mediaFiles) {
                me.$store.commit('showLoading');//打开遮罩
                /*//遍历获取录制的文件（iOS只支持一次录制一个视频或音频）
                for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                    console.log(mediaFiles);
                    path = mediaFiles[i].fullPath;
                    myFileName = mediaFiles[i].name;

                    file = mediaFiles[i];//得到纯文件
                    console.log("录制成功！\n\n"
                        + "文件名：" + mediaFiles[i].name + "\n"
                        + "大小：" + mediaFiles[i].size + "\n\n"
                        + "localURL地址：" + mediaFiles[i].localURL + "\n\n"
                        + "fullPath地址：" + path);
                }*/

                me.path = mediaFiles[0].fullPath;
                me.myFileName = mediaFiles[0].name;
                me.file = mediaFiles[0];//得到json{}纯文件
                console.log("录制成功！\n\n"
                    + "文件名：" + me.file.name + "\n"
                    + "大小：" + me.file.size + "\n\n"
                    + "localURL地址：" + me.file.localURL + "\n\n"
                    + "fullPath地址：" + me.path);
                //调用上传录音方法，先获取经纬度，在方法里面调用上传插件
                me.getLocaltion();

                /*fileUpload(path);
                function fileUpload(fileURL) {
                    console.log('-------------文件上传服务---------调用中');
                    console.log('fileURL', fileURL)
                    return new Promise(async (resolve, reject) => {
                        let param = new FormData();
                        let fileEntry = await asyncResolveLocalFileSystemURL(fileURL)
                        let file = await asyncFileEntry(fileEntry)
                        let imgBlob = await asyncFileReader(file)
                        param.append('file', imgBlob, myFileName);
                        param.append('longitude',me.longitude);
                        param.append('latitude',me.latitude);
                        param.append('userId',me.sid);
                        param.append('workModeId',me.workModeId);
                        param.append('time',me.createTime);
                        let config = {
                            headers: {
                                'Content-Type': 'multipart/form-data',
                                "Authorization":me.Authorization,
                                "gis4_imei":me.gis4_imei,
                                "gis4_time":new Date().getTime(),
                                "gis4_phone":me.gis4_phone,

                            },
                        }
                        // 添加请求头
                        axios.post('http://'+localStorage.getItem("apiHost")+'/app/work/upload',param, config).then(res=>{
                            if(res.status === 200){
                                me.mySoundInfo.fileName = myFileName;
                                me.mySoundInfo.createTime = me.createTime;
                                me.mySoundInfo.isOk = "1";
                                me.mySoundInfo.sid = me.sid;
                                me.reportHistory.push(me.mySoundInfo);
                                localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                                me.$store.commit('hideLoading');
                                me.isOk = "1";
                            }
                        }).catch((error) =>{
                            console.log("录音信息提交失败");
                            console.log(error);
                            me.mySoundInfo.fileName = myFileName;
                            me.mySoundInfo.createTime = me.createTime;
                            me.mySoundInfo.isOk = "0";
                            me.mySoundInfo.sid = me.sid;
                            me.reportHistory.push(me.mySoundInfo);
                            localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                            me.$store.commit('hideLoading');
                            me.isOk = "0";
                        })
                    })
                }*/

                function asyncResolveLocalFileSystemURL(fileURL) {
                    return new Promise((resolve, reject) => {
                        window.resolveLocalFileSystemURL(fileURL, fileEntry => {
                            resolve(fileEntry)
                        })
                    }, e => {
                        reject(e)
                    }, e => {
                        reject(e)
                    })
                }

                function asyncFileEntry(fileEntry) {
                    return new Promise((resolve, reject) => {
                        fileEntry.file(function (file) {
                            resolve(file)
                        }, function (e) {
                            reject(e)
                        });
                    })
                }

                function asyncFileReader(file, type = "audio/3gpp") {
                    return new Promise((resolve, reject) => {
                        try {
                            let reader = new FileReader();
                            reader.onloadend = function (e) {
                                let imgBlob = new Blob([this.result], {
                                    type
                                });
                                resolve(imgBlob)
                            };
                            reader.readAsArrayBuffer(file);
                        } catch (err) {
                            reject(err)
                        }
                    })
                }

            }

            //调用开始录音方法
            navigator.device.capture.captureAudio(onSuccess, onError, {limit: 1});

        },
        chooseAudio() {
                let me = this;
            console.log('我要选择录音');
            let success = function(result){
                if (result.length > 0) {
                    me.$store.commit('showLoading'); //打开遮罩
                    console.log("选择录音成功",result);
                    //返回的数据一个为jsonArray，一个图片有未压缩地址filePath和压缩地址compressPath，循环得乘以2
                    for(let i = 0;i<(result.length)/2;i++){
                        me.path = result[2*i+1];//这里取压缩地址，未压缩地址为：result[2*i]
                        let arrName = result[2*i+1].split("/");
                        me.myFileName = arrName[(arrName.length) - 1];
                        me.getLocaltion();
                    }
                }
            };
            let fail = function(error){
                me.$store.commit("hideLoading");
                console.log("返回Voice选择结果失败",error);

            };
            myMediaPlugin.selectVoice(success,fail,{message:"随便"});
        },
        generateFileName(date) {
            return date.getFullYear().toString() + "-" + complement(date.getMonth() + 1) + "-" +
                complement(date.getDate()) + " " + complement(date.getHours()) + ":" +
                complement(date.getMinutes()) + ":" + complement(date.getSeconds());

            function complement(n) {
                return n < 10 ? '0' + n : n
            }
        },

        //绑定显示上传进度
        selectload(e) {
            let me = this;
            if (e.lengthComputable) {
                // this.sheetVisible=true;
                let num = (e.loaded / e.total) * 100;
                me.progress = num.toFixed(2) + "%";
                /*console.log('当前进度：' + e.loaded / e.total);0.97*/
            }
        },
        getLocaltion() {
            let me = this;
            let nowTime = new Date();
            me.createTime = me.generateFileName(nowTime);
            baidumap_location.getCurrentPosition(result => {
                    console.log("上传文件调用经纬度:",result);
                    if(result.longitude===""||typeof (result.longitude)==="undefined"){
                        result.longitude = localStorage.getItem("longitude");
                        result.latitude = localStorage.getItem("latitude");
                    }
                    let params = {
                        LongitudeGcj02:result.longitude,
                        LatitudeGcj02:result.latitude,
                        userId:me.sid,
                        workModeId:me.workModeId,
                        time:me.createTime,
                    };
                    me.$store.commit("updateLatitude",result.latitude);
                    me.$store.commit("updateLongitude",result.longitude);
                    me.beginUpload(params);
                },error => {
                    console.log(error);
                    me.$store.commit('hideLoading');
                //CoorType: "gcj02", OpenAutoNotifyMode: false, ScanSpan: 0, LocationNotify: true
            },{CoorType:"gcj02",OpenAutoNotifyMode:true,Interval:5000,Distance:1,LocationNotify: true});
        },
        beginUpload (params) {
            let me = this;
            //上传成功的回调方法
            let win = function(r) {
                console.log(r);
                /*console.log("Code = " + r.responseCode);
                console.log("Sent = " + r.bytesSent);*/
                console.log("Response = " + r.response);

                //将上传信息放入本地上传历史资料信息显示
                me.$store.commit('hideLoading');
                me.isOk = "1";
                me.myVideoInfo.fileName = me.myFileName;
                me.myVideoInfo.createTime = me.createTime;
                me.myVideoInfo.sid = me.sid;
                me.myVideoInfo.isOk = "1";
                me.reportHistory.push(me.myVideoInfo);
                localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
            };
            //上传失败的回调方法
            let fail = function(error) {
                console.log("视频拍摄上传失败",error);
                /*console.log("An error has occurred: Code = " + error.code);
                console.log("upload error source " + error.source);
                console.log("upload error target " + error.target);*/
                me.$store.commit('hideLoading');
                me.isOk = "0";
                me.myVideoInfo.fileName = me.myFileName;
                me.myVideoInfo.createTime = me.createTime;
                me.myVideoInfo.isOk = "0";
                me.myVideoInfo.sid = me.sid;
                me.reportHistory.push(me.myVideoInfo);
                localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
            };
            //上传参数
            let options = new FileUploadOptions();
            options.fileKey = 'file';
            options.fileName = me.path.substr(me.path.lastIndexOf('/') + 1);
            options.mimeType = "audio/3gpp";
            let headers = {
                /*"Content-Type":'multipart/form-data'*/
                "Authorization":me.Authorization,
                "WorkPlanNo":me.$store.state.planNo,
                "gis4_longitude":localStorage.getItem("longitude"),
                "gis4_latitude": localStorage.getItem('latitude'),
                "gis4_imei" : localStorage.getItem('gis4_imei'),
                "gis4_phone" : localStorage.getItem('gis4_phone'),
                "version" : localStorage.getItem('version'),
                "gis4_workmode" :localStorage.getItem('workModeId'),
                "gis4_time":new Date().getTime()
            };
            options.headers = headers;
            options.params = params;
            //实例化上传类
            let ft = new FileTransfer();
            //绑定上传进度函数
            ft.onprogress = me.selectload;
            //开始上传 上传插件方法调用
            ft.upload(me.path, encodeURI('http://'+localStorage.getItem("apiHost")+'/app/work/upload'), win, fail,options);

        },

        }//method结束
    }
</script>

